package com.bobi.tfca.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobi.tfca.dao.GroupMessageDao;
import com.bobi.tfca.model.entity.GroupEntity;
import com.bobi.tfca.model.entity.GroupMemberEntity;
import com.bobi.tfca.model.entity.GroupMessageEntity;
import com.bobi.tfca.model.vo.ChatRoom;
import com.bobi.tfca.service.GroupMemberService;
import com.bobi.tfca.service.GroupMessageService;
import com.bobi.tfca.service.GroupService;
import com.bobi.tfca.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 群消息服务层实现
 * @author 李文发
 * @date 2024/4/3
 */
@Service
@Slf4j
public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageDao, GroupMessageEntity> implements GroupMessageService {

    @Autowired
    private GroupMemberService groupMemberService;

    @Autowired
    private GroupMessageDao groupMessageDao;

    @Override
    public Boolean checkNewGroupMsg(Integer memberId) {
        // 查询用户的所有群
        LambdaQueryWrapper<GroupMemberEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        List<GroupMemberEntity> list = groupMemberService.list(queryWrapper1.eq(GroupMemberEntity::getMemberId, memberId));
        // 根据id查询所有用户
        for (GroupMemberEntity groupMember : list) {
            GroupEntity groupEntity = groupMessageDao.getGroupByGroupId(groupMember.getGroupId());

            long count = getUnReadMessageNum(memberId, groupEntity.getGroupId());
            // 如果有消息就返回
            if (count > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public long getUnReadMessageNum(Integer memberId, Integer groupId) {
        return groupMessageDao.getUnReadMessageNum(memberId, groupId);
    }

    @Override
    public List<GroupMessageEntity> getGroupMessages(Integer groupId) {
        return this.list(new LambdaQueryWrapper<GroupMessageEntity>().eq(GroupMessageEntity::getGroupId, groupId));
    }

    @Override
    public void deleteGroupMessages(Integer groupId) {
        this.remove(new LambdaQueryWrapper<GroupMessageEntity>().eq(GroupMessageEntity::getGroupId, groupId));
    }

    @Override
    public void removeMessageByMessageId(Long messageId) {
        groupMessageDao.removeMessageByMessageId(messageId);
    }
}
